package com.dragee.modules.work.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dragee.modules.exportEntity.*;
import com.dragee.modules.work.dto.TeamPerson;
import com.dragee.modules.work.entity.*;
import com.dragee.modules.work.service.*;
import com.dragee.utils.excel.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author tys on 2023/8/10
 */
@RestController
@RequestMapping("work/export")
@Api(tags = "work - 导出")
public class ExportController {
    @Autowired
    private CompetitionService competitionService;
    @Autowired
    private CompetitionProjectService competitionProjectService;
    @Autowired
    private ApplyService applyService;
    @Autowired
    private TeamService teamService;
    @Autowired
    private CompetitionOrderService competitionOrderService;

// ======================================审核报名===================================

    @ApiOperation(value = "参赛单位表格数据")
    @GetMapping("/exportApplyUnit")
    public void exportApplyUnit(String competitionId, String status, String title , HttpServletResponse response) throws Exception {
        List<ApplyEntity> applys = baseData(competitionId, status, title);
        List<JoinUnitExport> datas = new ArrayList<>();
        for (ApplyEntity apply : applys) {
            JoinUnitExport export = new JoinUnitExport();
            export.setTeam(apply.getTeamName());
            List<TeamPerson> coachs = apply.getCoachs();
            String coachNames = ArrayUtil.join(coachs.stream().map(TeamPerson::getName).toArray(), ", ");
            String coachTels = ArrayUtil.join(coachs.stream().map(TeamPerson::getTel).toArray(), ", ");
            export.setCoach(coachNames);
            export.setCoachTel(coachTels);
            List<TeamPerson> leaders = apply.getLeaders();
            String leaderNames = ArrayUtil.join(leaders.stream().map(TeamPerson::getName).toArray(), ", ");
            String leaderTels = ArrayUtil.join(leaders.stream().map(TeamPerson::getTel).toArray(), ", ");
            export.setLeader(leaderNames);
            export.setLeaderTel(leaderTels);
            export.setCompetition(apply.getCompetitionName());
            datas.add(export);
        }
        ExcelUtils.writeExcel(response,
                datas,"参赛单位表格数据",
                "数据", JoinUnitExport.class);
    }


    @ApiOperation(value = "男女运动员数表格")
    @GetMapping("/exportSexAthleteSum")
    public void exportSexAthleteSum(String competitionId, String status, String title ,  HttpServletResponse response) throws Exception {
        List<ApplyEntity> applys = baseData(competitionId, status, title);
        List<SexAthleteSumExport> datas = new ArrayList<>();
        for (ApplyEntity apply : applys) {
            SexAthleteSumExport export = new SexAthleteSumExport();
            export.setTeam(apply.getTeamName());
            List<TeamPerson> coachs = apply.getCoachs();
            export.setCoachSum_m(coachs.stream().filter(t -> "男".equals(t.getSex())).count());
            export.setCoachSum_w(coachs.stream().filter(t -> "女".equals(t.getSex())).count());
            List<TeamPerson> leaders = apply.getLeaders();
            export.setLeaderSum_m(leaders.stream().filter(t -> "男".equals(t.getSex())).count());
            export.setLeaderSum_w(leaders.stream().filter(t -> "女".equals(t.getSex())).count());
            List<TeamPerson> others = apply.getOthers();
            export.setOtherSum_m(others.stream().filter(t -> "男".equals(t.getSex())).count());
            export.setOtherSum_v(others.stream().filter(t -> "女".equals(t.getSex())).count());

            Long athleteSum_m = 0L;
            Long athleteSum_w = 0L;
            List<ApplyProjectEntity> projects = apply.getProjects();
            for (ApplyProjectEntity project : projects) {
                List<TeamPerson> athletes = project.getAthletes();
                athleteSum_m = athleteSum_m + athletes.stream().filter(t -> "男".equals(t.getSex())).count();
                athleteSum_w = athleteSum_w + athletes.stream().filter(t -> "女".equals(t.getSex())).count();
            }
            export.setAthleteSum_m(athleteSum_m);
            export.setAthleteSum_w(athleteSum_w);
            export.setCompetition(apply.getCompetitionName());
            datas.add(export);
        }
        ExcelUtils.writeExcel(response,
                datas,"男女运动员数表格",
                "数据", SexAthleteSumExport.class);
    }


    @ApiOperation(value = "随队裁判表格")
    @GetMapping("/exportReferee")
    public void exportReferee(String competitionId, String status, String title ,  HttpServletResponse response) throws Exception {
        List<ApplyEntity> applys = baseData(competitionId, status, title);

        List<TeamRefereeExport> datas = new ArrayList<>();
        for (ApplyEntity apply : applys) {
            List<TeamPerson> referees = apply.getReferees();
            if (referees != null) {
                for (TeamPerson referee : referees) {
                    TeamRefereeExport export = new TeamRefereeExport();
                    export.setTeam(apply.getTeamName());
                    export.setCompetition(apply.getCompetitionName());
                    export.setName(referee.getName());
                    export.setSex(referee.getSex());
                    export.setIdCard(referee.getIdCard());
                    export.setTel(referee.getTel());
                    datas.add(export);
                }
            }
        }
        ExcelUtils.writeExcel(response,
                datas,"随队裁判表格",
                "数据", TeamRefereeExport.class);
    }

    @ApiOperation(value = "随队教练表格")
    @GetMapping("/exportCoach")
    public void exportCoach(String competitionId, String status, String title ,  HttpServletResponse response) throws Exception {
        List<ApplyEntity> applys = baseData(competitionId, status, title);

        List<TeamRefereeExport> datas = new ArrayList<>();
        for (ApplyEntity apply : applys) {
            List<TeamPerson> coachs = apply.getCoachs();
            if (coachs != null) {
                for (TeamPerson coach : coachs) {
                    TeamRefereeExport export = new TeamRefereeExport();
                    export.setTeam(apply.getTeamName());
                    export.setCompetition(apply.getCompetitionName());
                    export.setName(coach.getName());
                    export.setSex(coach.getSex());
                    export.setIdCard(coach.getIdCard());
                    export.setTel(coach.getTel());
                    datas.add(export);
                }
            }
        }
        ExcelUtils.writeExcel(response,
                datas,"随队教练表格",
                "数据", TeamCoachExport.class);
    }


    @ApiOperation(value = "费用导出表格")
    @GetMapping("/exportCost")
    public void exportCost(String competitionId, String status, String title ,  HttpServletResponse response) throws Exception {
        List<ApplyEntity> applys = baseData(competitionId, status, title);
        List<CostExport> datas = new ArrayList<>();
        for (ApplyEntity apply : applys) {
            List<ApplyProjectEntity> projects = apply.getProjects();
            CompetitionEntity competition = competitionService.getById(apply.getCompetitionId());
            for (int i = 0; i < projects.size(); i++) {
                ApplyProjectEntity project = projects.get(0);
                CostExport ex = new CostExport();
                ex.setTeam(apply.getTeamName());
                ex.setCompetition(apply.getCompetitionName());
                ex.setProject(project.getProjectName());
                ex.setGroup(project.getGroups());
                CompetitionProjectEntity competitionProject = competitionProjectService.getById(project.getProjectId());
                ex.setBaoMingStand(bigDecimalToStr(competitionProject.getEntryPrice()));
                ex.setBaoMingCostAll(bigDecimalToStr(apply.getEntryCost()));
                ex.setAthleteSum(project.getAthletes().size() + "");
                if (i == 0) {
                    ex.setCoachSum(apply.getCoachs().size() + "");
                    ex.setCoachBaoMingStand(bigDecimalToStr(competition.getCoachPrice()));
                    ex.setCoachBaoMingCostAll(bigDecimalToStr(apply.getCoachCost()));
                    ex.setLeaderSum(apply.getLeaders().size() + "");
                    ex.setLeaderBaoMingStand(bigDecimalToStr(competition.getLeaderPrice()));
                    ex.setLeaderBaoMingCostAll(bigDecimalToStr(apply.getLeaderCost()));
                    ex.setDanJianPrice(bigDecimalToStr(competition.getSingleRoomPrice()));
                    ex.setBiaoJianPrice(bigDecimalToStr(competition.getStandardRoomPrice()));
                    ex.setDanJianSum(apply.getSingleRoomPresonSum() + "");
                    ex.setBiaoJianSum(apply.getStandardRoomPersonSum() + "");
                    ex.setRootTotal(bigDecimalToStr(apply.getZhuSuCost()));
                    ex.setAllTotal(bigDecimalToStr(apply.getCost()));
                }
                datas.add(ex);
            }
        }
        ExcelUtils.writeExcel(response,
                datas,"费用导出表格",
                "数据", CostExport.class);
    }


    @ApiOperation(value = "综合报名表格导出")
    @GetMapping("/exportComprehensive")
    public void exportComprehensive(String competitionId, String status, String title ,  HttpServletResponse response) throws Exception {
        List<ApplyEntity> applys = baseData(competitionId, status, title);
        List<JoinComprehensiveExport> datas = new ArrayList<>();
        for (ApplyEntity apply : applys) {
            List<ApplyProjectEntity> projects = apply.getProjects();
            CompetitionEntity competition = competitionService.getById(apply.getCompetitionId());
            List<TeamPerson> coachs = apply.getCoachs();
            String coachNames = ArrayUtil.join(coachs.stream().map(TeamPerson::getName).toArray(), ", ");
            String coachTels = ArrayUtil.join(coachs.stream().map(TeamPerson::getTel).toArray(), ", ");
            long coachSum_m = coachs.stream().filter(t -> "男".equals(t.getSex())).count();
            long coachSum_w = coachs.stream().filter(t -> "女".equals(t.getSex())).count();
            List<TeamPerson> leaders = apply.getLeaders();
            String leaderNames = ArrayUtil.join(leaders.stream().map(TeamPerson::getName).toArray(), ", ");
            String leaderTels = ArrayUtil.join(leaders.stream().map(TeamPerson::getTel).toArray(), ", ");
            long leaderSum_m = leaders.stream().filter(t -> "男".equals(t.getSex())).count();
            long leaderSum_w = leaders.stream().filter(t -> "女".equals(t.getSex())).count();
            List<TeamPerson> others = apply.getOthers();
            String otherNames = ArrayUtil.join(others.stream().map(TeamPerson::getName).toArray(), ", ");
            long otherSum_m = others.stream().filter(t -> "男".equals(t.getSex())).count();
            long otherSum_w = others.stream().filter(t -> "女".equals(t.getSex())).count();
            List<TeamPerson> referees = apply.getReferees();
            long refereeSum_m = referees.stream().filter(t -> "男".equals(t.getSex())).count();
            long refereeSum_w = referees.stream().filter(t -> "女".equals(t.getSex())).count();
            String payJoinUrl = applyService.getJoinPayUrl(apply.getId().toString());
            List<TeamPerson> allPerson = new ArrayList<>();
            allPerson.addAll(leaders);
            allPerson.addAll(others);
            allPerson.addAll(coachs);
            allPerson.addAll(referees);
            List<JoinComprehensiveExport> tempDatas = new ArrayList<>();
            for (int i = 0; i < projects.size(); i++) {
                ApplyProjectEntity project = projects.get(i);
                JoinComprehensiveExport ex = new JoinComprehensiveExport();
                ex.setTeam(apply.getTeamName());
                ex.setProvince(apply.getTeamProvince());
                ex.setCity(apply.getTeamCity());
                ex.setOtherNames(otherNames);
                ex.setCompetition(apply.getCompetitionName());
                ex.setCoach(coachNames);
                ex.setCoachTel(coachTels);
                ex.setLeader(leaderNames);
                ex.setLeaderTel(leaderTels);
                ex.setRefereeSum_m(refereeSum_m);
                ex.setRefereeSum_w(refereeSum_w);
                ex.setCoachSum_m(coachSum_m);
                ex.setCoachSum_w(coachSum_w);
                ex.setLeaderSum_m(leaderSum_m);
                ex.setLeaderSum_w(leaderSum_w);
                ex.setOtherSum_m(otherSum_m);
                ex.setOtherSum_v(otherSum_w);
                ex.setProject(project.getProjectName());
                ex.setGroup(project.getGroups());
                List<TeamPerson> athletes = project.getAthletes();
                ex.setAthletes(ArrayUtil.join(athletes.stream().map(TeamPerson::getName).toArray(), ", "));
                long athleteSum_m = athletes.stream().filter(t -> "男".equals(t.getSex())).count();
                long athleteSum_w = athletes.stream().filter(t -> "女".equals(t.getSex())).count();
                ex.setAthleteSum_m(athleteSum_m);
                ex.setAthleteSum_w(athleteSum_w);
                ex.setAthleteSum(athleteSum_m + athleteSum_w);
                List<TeamPerson> projectCoachs = project.getProjectCoachs();
                String projectCoachNames = ArrayUtil.join(projectCoachs.stream().map(TeamPerson::getName).toArray(), ", ");
                ex.setProjectCoachs(projectCoachNames);
                ex.setDanJianSum(apply.getSingleRoomPresonSum());
                ex.setBiaoJianSum(apply.getStandardRoomPersonSum());
                ex.setBaoMingCost(bigDecimalToStr(apply.getEntryCost()));
                ex.setZhuSuCost(bigDecimalToStr(apply.getZhuSuCost()));
                ex.setCoachCost(bigDecimalToStr(apply.getCoachCost()));
                ex.setLeaderCost(bigDecimalToStr(apply.getLeaderCost()));
                ex.setAllCost(bigDecimalToStr(apply.getCost()));
                ex.setFptt(apply.getInvoiceTitle());
                ex.setSh(apply.getInvoiceTaxNumber());
                ex.setZhkhh(apply.getInvoiceBank());
                ex.setAddress(apply.getInvoiceBankAddress());
                ex.setInvoiceEmail(apply.getInvoiceEmail());bigDecimalToStr(apply.getZhuSuCost());
                ex.setTel(apply.getInvoiceTel());
                ex.setYinyuexiazai(applyService.getMusicUrl(project.getId().toString()));
                ex.setFeiyongpingzheng(payJoinUrl);
                allPerson.addAll(athletes);
                tempDatas.add(ex);
            }
            // 设置合计人数
            long allPersonSum = allPerson.stream().map(TeamPerson::getIdCard).distinct().count();
            tempDatas.forEach(d -> d.setAllPersonSum(allPersonSum));
            datas.addAll(tempDatas);
            tempDatas.clear();
        }
        ExcelUtils.writeExcel(response,
                datas,"综合报名表格导出",
                "数据", JoinComprehensiveExport.class);
    }


    @ApiOperation(value = "所有运动员信息导出")
    @GetMapping("/exportAllAthlete")
    public void exportAllAthlete(@RequestParam("competitionId") String competitionId,
                                    HttpServletResponse response ) throws Exception {
        List<Long> applyIds = applyService.list(new QueryWrapper<ApplyEntity>().select("id")
                .eq("competitionId", competitionId).orderByDesc("createTime"))
                .stream().map(ApplyEntity::getId).collect(Collectors.toList());
        List<AllAthleteExport> datas = new ArrayList<>();
        for (Long applyId : applyIds) {
            ApplyEntity apply = applyService.getApplyInfo(applyId.toString());
            List<ApplyProjectEntity> projects = apply.getProjects();
            List<TeamPerson> coachs = apply.getCoachs();
            String coachNames = ArrayUtil.join(coachs.stream().map(TeamPerson::getName).toArray(), ", ");
            List<TeamPerson> leaders = apply.getLeaders();
            String leaderNames = ArrayUtil.join(leaders.stream().map(TeamPerson::getName).toArray(), ", ");
            for (ApplyProjectEntity project : projects) {
                for (TeamPerson athlete : project.getAthletes()) {
                    AllAthleteExport ex = new AllAthleteExport();
                    ex.setTeam(apply.getTeamName());
                    ex.setStatus(apply.getStatus());
                    ex.setLeader(leaderNames);
                    ex.setCoach(coachNames);
                    ex.setProject(project.getProjectName());
                    ex.setType(project.getType());
                    ex.setGroups(project.getGroups());
                    ex.setCompetition(apply.getCompetitionName());
                    ex.setAthlete(athlete.getName());
                    ex.setIdCard(athlete.getIdCard());
                    ex.setSex(athlete.getSex());
                    ex.setAge(athlete.getAge());
                    datas.add(ex);
                }
            }

        }
         datas = datas.stream().distinct().collect(Collectors.toList());
        ExcelUtils.writeExcel(response,
                datas,"所有运动员信息",
                "数据", AllAthleteExport.class);
    }


// ======================================出场顺序===================================


    @ApiOperation(value = "出场顺序表格")
    @GetMapping("/exportOrder")
    public void exportOrder(String competitionId, String title , HttpServletResponse response) throws Exception {
        List<CompetitionOrderEntity> orders = baseDataOrder(competitionId, title);
        List<OrderExport> datas = new ArrayList<>();
        for (CompetitionOrderEntity order : orders) {
            if (StrUtil.isBlank(order.getApplyProjectIds())) {
                continue;
            }
            String[] applyProjectIds = order.getApplyProjectIds().split(",");
            for (int i = 0; i < applyProjectIds.length; i++) {
                String applyProjectId = applyProjectIds[i];
                OrderExport ex = new OrderExport();
                ex.setTime(DateUtil.format(order.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
                ex.setOrder(order.getTitle());
                ex.setOrderSort(i+1);
                ApplyProjectEntity applyProject = applyService.getApplyProjectInfo(applyProjectId);
                ApplyEntity apply = applyService.getApplyInfo(applyProject.getApplyId());
                ex.setTeam(apply.getTeamName());
                List<TeamPerson> coachs = apply.getCoachs();
                String coachNames = ArrayUtil.join(coachs.stream().map(TeamPerson::getName).toArray(), ", ");
                List<TeamPerson> leaders = apply.getLeaders();
                String leaderNames = ArrayUtil.join(leaders.stream().map(TeamPerson::getName).toArray(), ", ");
                ex.setLeader(leaderNames);
                ex.setCoach(coachNames);
                ex.setProject(applyProject.getProjectName());
                ex.setGroups(applyProject.getGroups());
                ex.setAthletes(ArrayUtil.join(applyProject.getAthletes().stream().map(TeamPerson::getName).toArray(), ", "));
                ex.setMusicUrl("http://47.101.130.227:9000/api" + applyProject.getFileMusicUrl());
                ex.setCompetition(apply.getCompetitionName());
                datas.add(ex);
            }
        }
        ExcelUtils.writeExcel(response,
                datas,"出场顺序表格",
                "数据", OrderExport.class);
    }



    @ApiOperation(value = "运动员信息表导出")
    @GetMapping("/exportAthleteOrder")
    public void exportAthleteOrder(String competitionId, String title , HttpServletResponse response) throws Exception {
        List<CompetitionOrderEntity> orders = baseDataOrder(competitionId, title);
        List<OrderAthleteExport> datas = new ArrayList<>();
        for (CompetitionOrderEntity order : orders) {
            String[] applyProjectIds = order.getApplyProjectIds().split(",");
            for (int i = 0; i < applyProjectIds.length; i++) {
                String applyProjectId = applyProjectIds[i];
                ApplyProjectEntity applyProject = applyService.getApplyProjectInfo(applyProjectId);
                ApplyEntity apply = applyService.getApplyInfo(applyProject.getApplyId());
                List<TeamPerson> coachs = apply.getCoachs();
                String coachNames = ArrayUtil.join(coachs.stream().map(TeamPerson::getName).toArray(), ", ");
                List<TeamPerson> leaders = apply.getLeaders();
                String leaderNames = ArrayUtil.join(leaders.stream().map(TeamPerson::getName).toArray(), ", ");
                for (TeamPerson athlete : applyProject.getAthletes()) {
                    OrderAthleteExport ex = new OrderAthleteExport();
                    ex.setAthlete(athlete.getName());
                    ex.setIdCard(athlete.getIdCard());
                    ex.setLeader(leaderNames);
                    ex.setCoach(coachNames);
                    ex.setProject(applyProject.getProjectName());
                    ex.setGroups(applyProject.getGroups());
                    ex.setCompetition(apply.getCompetitionName());
                    ex.setTeam(apply.getTeamName());
                    ex.setTime(DateUtil.format(order.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
                    ex.setOrder(order.getTitle());
                    ex.setOrderSort(i+1);
                    datas.add(ex);
                }
            }
        }
        ExcelUtils.writeExcel(response,
                datas,"运动员信息表导出",
                "数据", OrderAthleteExport.class);
    }

    private String bigDecimalToStr (BigDecimal value) {
        if (value == null) {
            return "0.00";
        }
        return value.toString();
    }



    private List<CompetitionOrderEntity> baseDataOrder (String competitionId, String title) {
        QueryWrapper<CompetitionOrderEntity> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(competitionId)) {
            wrapper.eq("competitionId", competitionId);
        }
        if (StrUtil.isNotBlank(title)) {
            wrapper.like("title", title);
        }
        wrapper.orderByDesc("sort");
        return competitionOrderService.list(wrapper);
    }

    private List<ApplyEntity> baseData (String competitionId,
                                        String status,
                                        String title) {
        QueryWrapper<ApplyEntity> wrapper = new QueryWrapper<>();
        wrapper.select("id");
        if (StrUtil.isNotBlank(competitionId)) {
            wrapper.eq("competitionId", competitionId);
        }
        if (StrUtil.isNotBlank(status)) {
            wrapper.eq("status", status);
        }
        if (StrUtil.isNotBlank(title)) {
            wrapper.like("title", title);
        }
        wrapper.orderByDesc("sort");
        List<ApplyEntity> datas = applyService.list(wrapper);
        List<ApplyEntity> result = datas.stream().map(t -> applyService.getApplyInfo(t.getId().toString())).collect(Collectors.toList());
        return result;
    }
}
